package ads1ss09.pa1;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;

/*
 * WICHTIG:
 *
 * Nehmen Sie keine Aenderungen in dieser Klasse vor. Bei der Abgabe
 * werden diese Aenderungen verworfen und es koennte dadurch passieren,
 * dass Ihr Programm somit nicht mehr korrekt funktioniert.
 */

public final class InputScanner
{

public enum ValueType {
	INVALID,
	INSERT,
	REMOVE,
	FIND
};

private BufferedReader input;
private ValueType type;
private int value;
private int numActions;
private boolean debugRequested;
private String line;

public
InputScanner()
{
	this(System.in);
}

public
InputScanner( InputStream in )
{
	input = new BufferedReader(new InputStreamReader(in));
	type = ValueType.INVALID;
	value = 0;
	numActions = -1;
	debugRequested = false;
	line = "#";
}

public ValueType
getType()
{
	return type;
}

public int
getValue() throws Exception
{
	if (type == ValueType.INVALID) {
		throw new Exception("InputScanner#getValue() called while "
			+ "scanner was in invalid state.");
	}

	return value;
}

public boolean
debugRequested()
{
	boolean ret = debugRequested;

	debugRequested = false;

	return ret;
}

public int
getNumActions()
{
	return numActions;
}

public boolean
nextValue() throws IOException
{
	if (line == null) return false;

	line = input.readLine();
	while (line != null && line.isEmpty()) line = input.readLine();

	while (line != null
			&& (line.charAt(0) == '#'
			|| type == ValueType.INVALID)) {

		if (line.startsWith("#numActions") && numActions < 0) {
			numActions = Integer.parseInt(line.substring(12));
		} else if (line.startsWith("#insert")) {
			type = ValueType.INSERT;
		} else if (line.startsWith("#remove")) {
			type = ValueType.REMOVE;
		} else if (line.startsWith("#find")) {
			type = ValueType.FIND;
		} else if (line.startsWith("#debug")) {
			debugRequested = true;
		}

		line = input.readLine();
		while (line != null && line.isEmpty()) line = input.readLine();
	}

	if (line == null) {
		type = ValueType.INVALID;
		value = 0;

		return false;
	}

	value = Integer.parseInt(line);

	return true;
}

} // class InputScanner
